package com.pubinfo.passbook.api.controller.auth;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.pubinfo.passbook.api.eip.UserInfoService;
import com.pubinfo.passbook.api.vat.ForwardVATService;
import com.pubinfo.passbook.common.entity.TPassbook;
import com.pubinfo.passbook.common.entity.TSystemRole;
import com.pubinfo.passbook.common.mapper.TSourcePassbookMapper;
import com.pubinfo.passbook.common.mapper.TSubsidiaryPrivateKeyMapper;
import com.pubinfo.passbook.common.model.bo.SubsidiaryInfo;
import com.pubinfo.passbook.common.model.dto.financial.*;
import com.pubinfo.passbook.common.model.vo.PassbookVo;
import com.pubinfo.passbook.common.model.vo.base.JsonResult;
import com.pubinfo.passbook.common.model.vo.base.MyPage;
import com.pubinfo.passbook.common.service.dedicated.DedicatedService;
import com.pubinfo.passbook.common.service.master.TPassbookService;
import com.pubinfo.passbook.common.service.request.financial.RequestFinancialServer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("passbook")
@Api(tags = "票据管理")
@Slf4j
public class TPassbookController {
  @Autowired
  TPassbookService passbookService;
  @Autowired
  TSourcePassbookMapper passbookMapper;
  @Autowired
  private TSubsidiaryPrivateKeyMapper keyMapper;
  @Autowired
  RequestFinancialServer financialServer;
  @Autowired
  ForwardVATService vatService;
  @Autowired
  DedicatedService dedicatedService;
  @Autowired
  UserInfoService userInfoService;
  
  @PostMapping("list")
  @ApiOperation("查询列表数据")
  public JsonResult<MyPage<PassbookVo>> listInterfaceClassify(@RequestBody final PassbookPageParamObj paramObj) {
    final TSystemRole role = this.userInfoService.getRoleInfo();
    return JsonResult.success(new MyPage(this.passbookService.listTPassbook(paramObj, role, this.userInfoService.getCurrentAcctId())));
  }
  
  @PostMapping("listByAcct")
  @ApiOperation("查询员工的票据")
  public JsonResult<MyPage<PassbookVo>> listByAcct(@RequestBody final PassbookPageParamObj paramObj) {
    final TSystemRole role = this.userInfoService.getRoleInfo();
    paramObj.setPayerPartyType("1");//只查询个人票据
    paramObj.setInvoiceStatus(1); //过滤冲红票据
  
    return JsonResult.success(new MyPage(this.passbookService.listTPassbook(paramObj, role, this.userInfoService.getCurrentAcctId())));
  }
  
  //  @PostMapping("listByAcct")
//  @ApiOperation(value = "查询当前登录人的票据")
//  public JsonResult<Page<PassbookVo>> listByAcct(@RequestBody UserPassbookListParam listParam) {
//
//    return JsonResult.page(passbookService.findAutoReimbursementByStaffCode(listParam, userInfoService.getRoleInfo(), userInfoService.getCurrentUserNsrsbh()));
//  }
//
  @GetMapping("details/{id}")
  @ApiOperation("查询详情")
  public JsonResult<InvoiceResult<Result>> details(@PathVariable("id") final String eInvoiceId) {
    return this.vatService.detailTPassbook(eInvoiceId);
  }
  
  @PutMapping("repair")
  @ApiOperation("修复数据")
  public JsonResult<Boolean> repair(@RequestBody final String[] eInvoiceIds) {
    QueryWrapper<TPassbook> queryWrapper = new QueryWrapper<>();
    queryWrapper.in("e_invoice_id", CollectionUtils.arrayToList(eInvoiceIds));
    //按公司分组，查询详情后设置数据
    List<TPassbook> passbookList = passbookService.list(queryWrapper);
    List<TPassbook> newPassbook = new ArrayList<>();
    if (!CollectionUtils.isEmpty(passbookList)) {
      Map<String, List<TPassbook>> nsrsbhMap = passbookList.stream().collect(Collectors.groupingBy(TPassbook::getNsrsbh));
      for (Map.Entry<String, List<TPassbook>> entry : nsrsbhMap.entrySet()) {
        String nsrsbh = entry.getKey();
        List<TPassbook> passbooks = entry.getValue();
        List<SubsidiaryInfo> subsidiaryInfos = keyMapper.listFinAllSubsidiaryInfo(nsrsbh);
        newPassbook.addAll(financialServer.setJson(passbooks, subsidiaryInfos.get(0)));
      }
    }
    return JsonResult.success(this.passbookService.updateBatchById(newPassbook));
  }
  
  @PostMapping("detailsBatch")
  @ApiOperation("批量查询详情")
  public InvoiceResult<Result> details(@RequestBody final String[] eInvoiceIds) {
    return this.vatService.detailTPassbook(eInvoiceIds);
  }
  
  @PostMapping("cancelLockedList")
  @ApiOperation("批量解锁票据")
  public InvoiceResult<Object> cancelLockedList(@RequestBody final String[] eInvoiceIds) {
    final List<CancelLockedRecord> cancelLockedRecords = CancelLockedRecord.toList(eInvoiceIds);
    final InvoiceResult<Object> invoiceResult = this.financialServer.cancelLockedList(cancelLockedRecords, "取消");
    if (invoiceResult.getSuccess()) {
      final UpdateWrapper<TPassbook> updateWrapper = new UpdateWrapper<>();
      updateWrapper.in("e_invoice_id", CollectionUtils.arrayToList(eInvoiceIds));
      updateWrapper.set("is_locked", "N");
      this.passbookService.update(updateWrapper);
    }
    return invoiceResult;
  }
  
  @DeleteMapping("remove/{eInvoiceId}")
  @ApiOperation("删除一条")
  public JsonResult<Boolean> delete(@PathVariable("eInvoiceId") final String eInvoiceId) {
    return JsonResult.success(this.passbookService.removeById(eInvoiceId));
  }
  
  @PostMapping("removeBatch")
  @ApiOperation("批量删除")
  public JsonResult<Boolean> delete(String[] eInvoiceIds) {
    return JsonResult.success(this.passbookService.removeByIds(CollectionUtils.arrayToList(eInvoiceIds)));
  }
  
  @PostMapping("selectByAcct")
  @ApiOperation("医疗费报账页面-票据列表")
  public JsonResult<MyPage<TPassbook>> selectTPassbook(@RequestBody final PassbookParamAcct acct) {
    return JsonResult.success(new MyPage(this.passbookService.selectTPassbookByAcct(acct)));
  }
  
  @PostMapping("selectPassbookByFpdmAndFphm")
  @ApiOperation("利用票据编号和票据代码查询票据内容")
  public JsonResult<List<TPassbook>> selectPassbookByFpdmAndFphm(@RequestBody final List<TPassbook> Passbook) {
    return JsonResult.success(this.passbookService.selectPassbookByFpdmAndFphm(Passbook));
  }
  
  @PostMapping("detailsByIdAndNsrsbh")
  @ApiOperation("根据id和公司查询票据详情")
  public JsonResult<String> detailsByIdAndNsrsbh(@RequestBody final PassbookDetailsParam param) {
    return JsonResult.success(this.dedicatedService.getPassbookDetails(param));
  }
//
//  @PostMapping("downLoadPDF")
//  @ApiOperation(value = "根据id下载PDF")
//  public void downLoadPDF() throws IOException, UnirestException {
//    passbookService.downLoadPDF();
//  }
//
}
